package com.wyg.demo.controller;

import com.wyg.demo.common.CommonResult;
import com.wyg.demo.common.OperateMenu;
import com.wyg.demo.common.OperateType;
import com.wyg.demo.common.utils.CsvUtil;
import com.wyg.demo.domain.CsvDirPath;
import com.wyg.demo.service.LongDistanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ygWen
 * @Description: 操作csv文件 控制器
 * @date 2021/12/30
 */
@RestController
public class LongDistanceController {
    @Autowired
    private LongDistanceService longDistanceService;

    /**
     * 将指定目录下的所有csv文件中的数据导入到数据库中
     * @param csvDirPath csv文件所在目录路径
     * @return 结果
     */
    @PostMapping("/csvBatchImport")
    @OperateType(menu = OperateMenu.MENU_CSV_DATA, operateType = OperateMenu.OPERATE_IMPORT)
    public CommonResult<Void> csvBatchImport(@RequestBody CsvDirPath csvDirPath) throws IOException {
        longDistanceService.csvInsert(csvDirPath.getDirPath());
        return CommonResult.success();
    }

    /**
     * 将数据写入csv文件并下载
     * @param response 响应对象
     */
    @PostMapping("/download")
    @OperateType(menu = OperateMenu.MENU_CSV_DATA, operateType = OperateMenu.OPERATE_DOWNLOAD)
    public CommonResult<Void> csvDownload(HttpServletResponse response){
        byte[] bytes = longDistanceService.exportCsv();
        CsvUtil.responseSetProperties("longDistance.csv", bytes, response);
        return CommonResult.success();
    }
}
